/**   
 * @Project: jinlele-back 
 * @Title: AccessTokenUtil.java 
 * @Package com.tz.util.weixinUtils.vo 
 * @Description: TODO 
 * @author yangcd 
 * @date 2017年6月15日 上午11:17:14 
 * @version V1.0   
 */
package com.jinlele.util.weixinUtils.vo;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jinlele.model.AccessToken;
import com.jinlele.service.interfaces.IAccessTokenService;
import com.jinlele.util.weixinUtils.util.Parameter;

/** 
 * @ClassName AccessTokenUtil  
 * @Description TODO 
 * @author yangcd 
 * @date 2017年6月15日  
 *   
 */
@Component
public class AccessTokenUtil {
	private static Logger logger = LoggerFactory.getLogger(AccessTokenUtil.class);
	
	//第三方用户唯一凭证
    private  static  String appid = Parameter.corId;
    //第三方用户唯一凭证密钥
    private  static  String appsecret = Parameter.appsecret;
	
	@Autowired  
    private IAccessTokenService accessTokenService;  
    private static AccessTokenUtil accessTokenUtil;  
  
    public void setAccessTokenService(IAccessTokenService accessTokenService) {  
        this.accessTokenService = accessTokenService;  
    }  
      
    @PostConstruct  
    private void init() {  
    	accessTokenUtil = this;  
    	accessTokenUtil.accessTokenService = this.accessTokenService;
    } 
    
    public static Token getAccessToken(){
    	AccessToken accessToken = accessTokenUtil.accessTokenService.getAccessToken();
    	Token token = new Token();
    	if(((System.currentTimeMillis() - accessToken.getCreate_time()) / 100) < (accessToken.getExpires_in()-10)){
    		logger.info("access_token：{}有效",accessToken.getAccess_token());
    		token.setAccessToken(accessToken.getAccess_token());
    		token.setExpiresIn(accessToken.getExpires_in());
    		token.setJsapiTicket(accessToken.getJsapi_ticket());
    	}else{
    		logger.info("access_token失效，重新获取");
    		token = WeiXinUtil.getToken(appid , appsecret);
    		String jsapi_ticket = WeiXinUtil.JSApiTIcket(token.getAccessToken());
    		token.setJsapiTicket(jsapi_ticket);
    		accessToken.setAccess_token(token.getAccessToken());
    		accessToken.setCreate_time(System.currentTimeMillis());
    		accessToken.setExpires_in(token.getExpiresIn());
    		accessToken.setJsapi_ticket(jsapi_ticket);
    		logger.info("==========存入更新后的access_token到数据库================");
    		accessTokenUtil.accessTokenService.update(accessToken);
    	}
    	return token;
    }
}
